<template>
  <div class="enhanced-stats-cards">
    <!-- 实时数据统计卡片 -->
    <div class="stats-section">
      <h3 class="section-title">
        <el-icon><DataAnalysis /></el-icon>
        实时数据统计
      </h3>
      <div class="stats-grid">
        <div class="stat-card pending">
          <div class="stat-icon">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.pendingTickets }}</div>
            <div class="stat-label">待处理</div>
            <div class="stat-change" :class="getChangeClass(stats.pendingChange)">
              <el-icon><component :is="getChangeIcon(stats.pendingChange)" /></el-icon>
              {{ Math.abs(stats.pendingChange) }}%
            </div>
          </div>
          <div class="stat-trend">
            <div class="trend-line" :style="{ height: getTrendHeight(stats.pendingTrend) }"></div>
          </div>
        </div>

        <div class="stat-card in-progress">
          <div class="stat-icon">
            <el-icon><Loading /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.inProgressTickets }}</div>
            <div class="stat-label">处理中</div>
            <div class="stat-change" :class="getChangeClass(stats.inProgressChange)">
              <el-icon><component :is="getChangeIcon(stats.inProgressChange)" /></el-icon>
              {{ Math.abs(stats.inProgressChange) }}%
            </div>
          </div>
          <div class="stat-trend">
            <div class="trend-line" :style="{ height: getTrendHeight(stats.inProgressTrend) }"></div>
          </div>
        </div>

        <div class="stat-card resolved">
          <div class="stat-icon">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.resolvedTickets }}</div>
            <div class="stat-label">已解决</div>
            <div class="stat-change" :class="getChangeClass(stats.resolvedChange)">
              <el-icon><component :is="getChangeIcon(stats.resolvedChange)" /></el-icon>
              {{ Math.abs(stats.resolvedChange) }}%
            </div>
          </div>
          <div class="stat-trend">
            <div class="trend-line" :style="{ height: getTrendHeight(stats.resolvedTrend) }"></div>
          </div>
        </div>

        <div class="stat-card overdue">
          <div class="stat-icon">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.overdueTickets }}</div>
            <div class="stat-label">逾期工单</div>
            <div class="stat-change" :class="getChangeClass(stats.overdueChange)">
              <el-icon><component :is="getChangeIcon(stats.overdueChange)" /></el-icon>
              {{ Math.abs(stats.overdueChange) }}%
            </div>
          </div>
          <div class="stat-trend">
            <div class="trend-line" :style="{ height: getTrendHeight(stats.overdueTrend) }"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 性能指标卡片 -->
    <div class="stats-section">
      <h3 class="section-title">
        <el-icon><TrendCharts /></el-icon>
        性能指标
      </h3>
      <div class="stats-grid">
        <div class="stat-card sla">
          <div class="stat-icon">
            <el-icon><Timer /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.slaRate }}%</div>
            <div class="stat-label">SLA达成率</div>
            <div class="stat-change" :class="getChangeClass(stats.slaChange)">
              <el-icon><component :is="getChangeIcon(stats.slaChange)" /></el-icon>
              {{ Math.abs(stats.slaChange) }}%
            </div>
          </div>
          <div class="progress-ring">
            <canvas ref="slaChartRef" width="60" height="60"></canvas>
          </div>
        </div>

        <div class="stat-card response-time">
          <div class="stat-icon">
            <el-icon><Stopwatch /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.avgResponseTime }}h</div>
            <div class="stat-label">平均响应时间</div>
            <div class="stat-change" :class="getChangeClass(stats.responseTimeChange)">
              <el-icon><component :is="getChangeIcon(stats.responseTimeChange)" /></el-icon>
              {{ Math.abs(stats.responseTimeChange) }}%
            </div>
          </div>
          <div class="time-chart">
            <canvas ref="responseTimeChartRef" width="60" height="40"></canvas>
          </div>
        </div>

        <div class="stat-card satisfaction">
          <div class="stat-icon">
            <el-icon><Star /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.satisfactionScore }}</div>
            <div class="stat-label">客户满意度</div>
            <div class="stat-change" :class="getChangeClass(stats.satisfactionChange)">
              <el-icon><component :is="getChangeIcon(stats.satisfactionChange)" /></el-icon>
              {{ Math.abs(stats.satisfactionChange) }}%
            </div>
          </div>
          <div class="satisfaction-stars">
            <el-rate
              v-model="stats.satisfactionScore"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 环比数据展示 -->
    <div class="stats-section">
      <h3 class="section-title">
        <el-icon><DataLine /></el-icon>
        环比数据对比
        <el-select v-model="comparisonPeriod" size="small" style="width: 120px; margin-left: 12px;">
          <el-option label="昨日" value="yesterday" />
          <el-option label="上周" value="lastWeek" />
          <el-option label="上月" value="lastMonth" />
        </el-select>
      </h3>
      <div class="comparison-grid">
        <div class="comparison-card">
          <div class="comparison-header">
            <span class="comparison-title">工单总量</span>
            <el-tag :type="getComparisonTagType(stats.totalTicketsChange)" size="small">
              {{ stats.totalTicketsChange > 0 ? '+' : '' }}{{ stats.totalTicketsChange }}%
            </el-tag>
          </div>
          <div class="comparison-content">
            <div class="current-value">{{ stats.totalTickets }}</div>
            <div class="previous-value">上期: {{ stats.previousTotalTickets }}</div>
          </div>
        </div>

        <div class="comparison-card">
          <div class="comparison-header">
            <span class="comparison-title">解决率</span>
            <el-tag :type="getComparisonTagType(stats.resolutionRateChange)" size="small">
              {{ stats.resolutionRateChange > 0 ? '+' : '' }}{{ stats.resolutionRateChange }}%
            </el-tag>
          </div>
          <div class="comparison-content">
            <div class="current-value">{{ stats.resolutionRate }}%</div>
            <div class="previous-value">上期: {{ stats.previousResolutionRate }}%</div>
          </div>
        </div>

        <div class="comparison-card">
          <div class="comparison-header">
            <span class="comparison-title">平均处理时间</span>
            <el-tag :type="getComparisonTagType(-stats.avgProcessingTimeChange)" size="small">
              {{ stats.avgProcessingTimeChange > 0 ? '+' : '' }}{{ stats.avgProcessingTimeChange }}%
            </el-tag>
          </div>
          <div class="comparison-content">
            <div class="current-value">{{ stats.avgProcessingTime }}h</div>
            <div class="previous-value">上期: {{ stats.previousAvgProcessingTime }}h</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  DataAnalysis, 
  Clock, 
  Loading, 
  Check, 
  Warning, 
  Timer, 
  Stopwatch, 
  Star, 
  DataLine,
  TrendCharts,
  ArrowUp,
  ArrowDown,
  Minus
} from '@element-plus/icons-vue'
import chartService, { chartColors } from '../services/chartService'
import dashboardApiService from '../services/dashboardApi'

export default {
  name: 'EnhancedStatsCards',
  components: {
    DataAnalysis,
    Clock,
    Loading,
    Check,
    Warning,
    Timer,
    Stopwatch,
    Star,
    DataLine,
    TrendCharts,
    ArrowUp,
    ArrowDown,
    Minus
  },
  setup() {
    const comparisonPeriod = ref('yesterday')
    const updateInterval = ref(null)
    const slaChartRef = ref(null)
    const responseTimeChartRef = ref(null)
    let slaChart = null
    let responseTimeChart = null
    
    // 统计数据
    const stats = ref({
      // 实时数据
      pendingTickets: 0,
      inProgressTickets: 0,
      resolvedTickets: 0,
      overdueTickets: 0,
      
      // 变化百分比
      pendingChange: 0,
      inProgressChange: 0,
      resolvedChange: 0,
      overdueChange: 0,
      
      // 趋势数据（用于小图表）
      pendingTrend: [],
      inProgressTrend: [],
      resolvedTrend: [],
      overdueTrend: [],
      
      // 性能指标
      slaRate: 0,
      slaChange: 0,
      avgResponseTime: 0,
      responseTimeChange: 0,
      responseTimeTrend: [],
      satisfactionScore: 0,
      satisfactionChange: 0,
      
      // 环比数据
      totalTickets: 0,
      totalTicketsChange: 0,
      previousTotalTickets: 0,
      resolutionRate: 0,
      resolutionRateChange: 0,
      previousResolutionRate: 0,
      avgProcessingTime: 0,
      avgProcessingTimeChange: 0,
      previousAvgProcessingTime: 0
    })
    
    // 方法
    const loadStatsData = async () => {
      try {
        // 调用后端API获取统计数据
        const data = await dashboardApiService.getDashboardStats()
        stats.value = { ...stats.value, ...data }
        
        // 渲染图表
        await nextTick()
        renderCharts()
      } catch (error) {
        console.error('加载统计数据失败:', error)
        ElMessage.error('加载统计数据失败')
      }
    }
    
    // 渲染所有图表
    const renderCharts = () => {
      renderSLAChart()
      renderResponseTimeChart()
    }
    
    // 渲染SLA达成率环形图
    const renderSLAChart = () => {
      if (!slaChartRef.value) return
      
      const slaRate = stats.value.slaRate || 0
      const remaining = 100 - slaRate
      
      const chartData = {
        labels: ['已达成', '未达成'],
        datasets: [{
          data: [slaRate, remaining],
          backgroundColor: [
            chartColors.success,
            'rgba(224, 224, 224, 0.3)'
          ],
          borderWidth: 0
        }]
      }
      
      const options = {
        responsive: true,
        maintainAspectRatio: true,
        plugins: {
          legend: {
            display: false
          },
          tooltip: {
            enabled: false
          }
        },
        cutout: '70%'
      }
      
      if (slaChart) {
        chartService.updateChart(slaChart, chartData)
      } else {
        slaChart = chartService.createDoughnutChart(slaChartRef.value, chartData, options)
      }
    }
    
    // 渲染响应时间趋势迷你折线图
    const renderResponseTimeChart = () => {
      if (!responseTimeChartRef.value) return
      
      const trendData = stats.value.responseTimeTrend || []
      const labels = trendData.map((_, index) => '')
      
      const chartData = {
        labels,
        datasets: [{
          data: trendData,
          backgroundColor: chartColors.infoLight,
          borderColor: chartColors.info,
          borderWidth: 2,
          tension: 0.4,
          fill: true,
          pointRadius: 0
        }]
      }
      
      const options = {
        responsive: true,
        maintainAspectRatio: true,
        plugins: {
          legend: {
            display: false
          },
          tooltip: {
            enabled: false
          }
        },
        scales: {
          x: {
            display: false
          },
          y: {
            display: false
          }
        }
      }
      
      if (responseTimeChart) {
        chartService.updateChart(responseTimeChart, chartData)
      } else {
        responseTimeChart = chartService.createLineChart(responseTimeChartRef.value, chartData, options)
      }
    }
    
    const getChangeClass = (change) => {
      if (change > 0) return 'positive'
      if (change < 0) return 'negative'
      return 'neutral'
    }
    
    const getChangeIcon = (change) => {
      if (change > 0) return ArrowUp  // ✅ 返回组件对象
      if (change < 0) return ArrowDown  // ✅ 返回组件对象
      return Minus  // ✅ 返回组件对象
    }
    
    const getTrendHeight = (trend) => {
      if (!trend || trend.length === 0) return '0%'
      const max = Math.max(...trend)
      const current = trend[trend.length - 1]
      return `${(current / max) * 100}%`
    }
    
    
    const getComparisonTagType = (change) => {
      if (change > 0) return 'success'
      if (change < 0) return 'danger'
      return 'info'
    }
    
    const startRealTimeUpdate = () => {
      // 每30秒更新一次数据
      updateInterval.value = setInterval(() => {
        loadStatsData()
      }, 30000)
    }
    
    const stopRealTimeUpdate = () => {
      if (updateInterval.value) {
        clearInterval(updateInterval.value)
        updateInterval.value = null
      }
    }
    
    // 生命周期
    onMounted(() => {
      loadStatsData()
      startRealTimeUpdate()
    })
    
    onUnmounted(() => {
      stopRealTimeUpdate()
      
      // 销毁图表实例
      if (slaChart) {
        chartService.destroyChart(slaChart)
      }
      if (responseTimeChart) {
        chartService.destroyChart(responseTimeChart)
      }
    })
    
    return {
      stats,
      comparisonPeriod,
      slaChartRef,
      responseTimeChartRef,
      getChangeClass,
      getChangeIcon,
      getTrendHeight,
      getComparisonTagType
    }
  }
}
</script>

<style scoped>
.enhanced-stats-cards {
  padding: 20px;
}

.stats-section {
  margin-bottom: 30px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid var(--border-primary);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #667eea, #764ba2);
}

.stat-card.pending::before {
  background: linear-gradient(90deg, #f093fb, #f5576c);
}

.stat-card.in-progress::before {
  background: linear-gradient(90deg, #4facfe, #00f2fe);
}

.stat-card.resolved::before {
  background: linear-gradient(90deg, #43e97b, #38f9d7);
}

.stat-card.overdue::before {
  background: linear-gradient(90deg, #fa709a, #fee140);
}

.stat-card.sla::before {
  background: linear-gradient(90deg, #a8edea, #fed6e3);
}

.stat-card.response-time::before {
  background: linear-gradient(90deg, #ffecd2, #fcb69f);
}

.stat-card.satisfaction::before {
  background: linear-gradient(90deg, #ff9a9e, #fecfef);
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  flex-shrink: 0;
}

.stat-card.pending .stat-icon {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.stat-card.in-progress .stat-icon {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.stat-card.resolved .stat-icon {
  background: linear-gradient(135deg, #43e97b, #38f9d7);
}

.stat-card.overdue .stat-icon {
  background: linear-gradient(135deg, #fa709a, #fee140);
}

.stat-card.sla .stat-icon {
  background: linear-gradient(135deg, #a8edea, #fed6e3);
}

.stat-card.response-time .stat-icon {
  background: linear-gradient(135deg, #ffecd2, #fcb69f);
}

.stat-card.satisfaction .stat-icon {
  background: linear-gradient(135deg, #ff9a9e, #fecfef);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: 800;
  color: var(--text-primary);
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 8px;
}

.stat-change {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 600;
}

.stat-change.positive {
  color: #10b981;
}

.stat-change.negative {
  color: #ef4444;
}

.stat-change.neutral {
  color: #6b7280;
}

.stat-trend {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: end;
  gap: 2px;
}

.trend-line {
  flex: 1;
  background: linear-gradient(to top, #667eea, #764ba2);
  border-radius: 2px;
  min-height: 4px;
  transition: height 0.3s ease;
}

.progress-ring {
  position: relative;
  width: 60px;
  height: 60px;
  flex-shrink: 0;
}

.progress-circle {
  transform: rotate(-90deg);
}

.progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 12px;
  font-weight: 600;
  color: var(--text-primary);
}

.time-chart {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: end;
  gap: 2px;
}

.time-point {
  flex: 1;
  background: linear-gradient(to top, #ffecd2, #fcb69f);
  border-radius: 2px;
  min-height: 4px;
  transition: height 0.3s ease;
}

.satisfaction-stars {
  flex-shrink: 0;
}

.comparison-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.comparison-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.comparison-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.comparison-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.comparison-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-secondary);
}

.comparison-content {
  text-align: center;
}

.current-value {
  font-size: 24px;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 4px;
}

.previous-value {
  font-size: 12px;
  color: var(--text-tertiary);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .enhanced-stats-cards {
    padding: 16px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .stat-card {
    padding: 20px;
  }
  
  .stat-icon {
    width: 50px;
    height: 50px;
    font-size: 20px;
  }
  
  .stat-number {
    font-size: 28px;
  }
  
  .comparison-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}

/* 暗色主题适配 */
.dark .stat-card {
  background: var(--bg-primary);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.dark .stat-card:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
}

.dark .comparison-card {
  background: var(--bg-primary);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.dark .comparison-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
}
</style>
